package gui;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import java.io.IOException;
import java.util.HashSet;

import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JList;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JOptionPane;
import javax.swing.JScrollPane;
import javax.swing.JSplitPane;

import reader.GeometryReader;

import model.DrawableListModel;
import model.IDrawable;

public class DrawFrame extends JFrame {
	
	
	private DrawableListModel theDrawableListModel;
	private DrawPanel theDrawPanel;

	public DrawFrame() {
		super();
		this.setSize(600, 400);
		this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		
		theDrawableListModel = new DrawableListModel();
		theDrawPanel = new DrawPanel(theDrawableListModel);
		JList list = new JList(theDrawableListModel);
		JScrollPane scrollPane = new JScrollPane(list);
		JSplitPane splitPane = new JSplitPane(JSplitPane.VERTICAL_SPLIT, theDrawPanel, scrollPane);
		splitPane.setDividerLocation(200);
		this.setContentPane(splitPane);
		initJMenuBar();
	}

	private void initJMenuBar() {
		JMenuBar menubar = new JMenuBar();
		JMenu menuFile = new JMenu("File");
		JMenuItem itemLoad = new JMenuItem("Load 2D Geometries");
		itemLoad.addActionListener(new ActionListener() {

			@Override
			public void actionPerformed(ActionEvent e) {
				JFileChooser fileChooser = new JFileChooser();
				int returnValue = fileChooser.showOpenDialog(DrawFrame.this);
				if(returnValue == JFileChooser.APPROVE_OPTION) {
					File selectedFile = fileChooser.getSelectedFile();
					GeometryReader reader = new GeometryReader(selectedFile);
					try {
						String readFile = reader.readFile();
						HashSet<IDrawable> theResultHashSet = reader.getTheResultHashSet();
						theDrawableListModel.addAll(theResultHashSet);
						theDrawPanel.repaint();
					} catch (IOException e1) {
						JOptionPane.showMessageDialog(DrawFrame.this, e1.getMessage());
					}
				}
			}});
		menuFile.add(itemLoad);
		menubar.add(menuFile);
		this.setJMenuBar(menubar);
		
	}

}
